#!usr/bin/env python3
#认证蓝本的路由定义
from flask import render_template,request,redirect,flash,url_for
from . import auth
from app.auth.form import LoginFrom,RegisterForm
from flask_login import login_user,login_required,logout_user,current_user
from ..models import User,commit #访问上层目录导入
from ..email import send_mail,send_confirm
import logging
from config import getLang #获取语言包的函数 getLang(key,args)

@auth.route("/login",methods=['GET','POST'])
def login():
	loginForm = LoginFrom()
	if loginForm.validate_on_submit():
		u = User.query.filter_by(email=loginForm.email.data).first() #查询第一条邮箱用户
		if u is not None and u.verify_password(loginForm.password.data):			
			login_user(u,loginForm.remenber_me)
			'''
			request.args.get("next") 如果存在该值表示用户未被授权 
			flask_login会自动跳转到登陆表单页面保存在request.args的next中
			'''
			nextUrl =  request.args.get("next")		
			if not nextUrl:
				flash(getLang("loginSuc"))	
			return redirect(nextUrl or url_for("main.index"))		
		flash(getLang("loginError"))	
	return render_template("auth/login.html",form=loginForm)

@auth.route("/logout")
@login_required
def logout():
	logout_user()
	flash(getLang("logout"))
	return redirect(url_for("main.index"))

@auth.route("/register",methods=["GET","POST"])
def register():
	form = RegisterForm()
	if form.validate_on_submit():
		u = User(
			email=form.email.data,
			username=form.username.data,
			password=form.password.data,
			)
		commit([u])
		send_confirm(u) #发送验证邮件
		flash(getLang('registeOk'))
		return redirect(url_for('auth.login'))
	return render_template("auth/register.html",form=form)

#邮件验证的视图函数
@auth.route("/confirm/<token>")
@login_required
def confirm(token):
	if current_user.confirmed:
		return redirect(url_for("main.index"))
	elif current_user.confirm(token):
		flash(getLang('confirMsg'))
	else:
		flash(getLang("confirError"))
	return redirect(url_for("main.index"))
@auth.route('/uncomfirmed')
@login_required
def uncomfirmed():
	return "<h1>请尽快验证你的账号</h1>"

@auth.before_app_request	
def before_request(): #每次请求前会调用的函数,通过蓝本自身的装饰器实现 
	if current_user.is_authenticated:
		current_user.ping() #每次收到用户的请求时都要执行该函数刷新上次登录时间
		#flash("请尽快验证您的账号")
		#if not current_user.confirmed and request.endpoint[:5]!='auth.':
			#return redirect(url_for('auth.uncomfirmed'))